//
//  Tools.m
//  婚礼记
//
//  Created by 月月 on 15/4/6.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "Tools.h"
#import <CommonCrypto/CommonDigest.h>
@implementation Tools

+ (NSString *)pathWithName:(NSString *)name directory:(NSSearchPathDirectory)directory
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES) lastObject];
    
    path = [NSString stringWithFormat:@"%@/123", path];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        [manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    path = [NSString stringWithFormat:@"%@/%@", path, name];
    return path;
}

+ (void)writeWithName:(NSString *)name data:(NSData *)data directory:(NSSearchPathDirectory)directory
{
    name = [Tools cachedFileNameForKey:name];
    
    NSString *path = [Tools pathWithName:name directory:directory];
    [data writeToFile:path atomically:YES];
}

+ (NSData *)readWithName:(NSString *)name directory:(NSSearchPathDirectory)directory
{
    name = [Tools cachedFileNameForKey:name];
    
    NSString *path = [Tools pathWithName:name directory:directory];
    NSData *data = [NSData dataWithContentsOfFile:path];
    if (data) {
        return data;
    }
    return [NSData data];
}


+ (NSString *)cachedFileNameForKey:(NSString *)key {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    return filename;
}


@end
